package com.ccp.dev.im.service;

import com.alibaba.fastjson.JSONObject;
import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.im.dao.ImRoomUserDao;
import com.ccp.dev.im.model.ImRoom;
import com.ccp.dev.im.model.ImRoomUser;
import com.ccp.dev.im.model.ImSystemMessage;
import com.ccp.dev.im.model.ImUser;
import com.ccp.dev.im.server.connertor.ImConnertor;
import com.ccp.dev.im.server.constant.Constants;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;

/**
 * 群聊成员 信息操作服务类
 *
 * @author y
 * @date 2020-02-17 11:39:36
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ImRoomUserService extends BaseService<ImRoomUser> {

    @Resource
    private ImRoomUserDao dao;

    @Resource
    private ImRoomService imRoomService;

    @Resource
    private ImUserService imUserService;

    @Resource
    private ImSystemMessageService imSystemMessageService;

    @Resource
    private ImConnertor imConnertorImpl;

    @Resource
    private ImRoomUserService  imRoomUserService;



    /**
     * 根据群ID查询群成员和群主信息
     *
     * @param roomId
     * @param queryFilter
     * @return
     */
    public Map<String, Object> getRoomUserInfoByRoomId(String roomId, QueryFilter queryFilter) {
        Map<String, Object> retMap = new HashMap<>();
        List<ImRoomUser> roomUsers = dao.queryList(queryFilter);
        ImRoom imRoom = imRoomService.getOneById(roomId);
        if (BeanUtils.isNotEmpty(imRoom)) {
            ImUser imUser = imUserService.getByUserId(imRoom.getUserId());
            retMap.put("owner", imUser);
        }
        retMap.put("list", roomUsers);
        retMap.put("members", roomUsers.size());
        return retMap;
    }

    /**
     * 根据群ID查询群成员ID集合
     *
     * @param roomId 群ID
     * @return 集合
     */
    public Set<String> getRoomUserIdsByRoomId(String roomId) {
        return dao.getRoomUserIdsByRoomId(roomId);
    }


    /**
     * 群聊里面邀请人员
     *
     * @param roomId  群ID
     * @param userIds 邀请人员数组
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int addRoomUsers(String roomId, String[] userIds, String[] addUserNames, boolean isCreate) {
        int count = 0;
        ImUser imUser = imUserService.getByUserId(ContextUtil.getCurrentUserId());
        ImRoom imRoom = imRoomService.getOneById(roomId);
        String content = "你已加入 \"" + imRoom.getRoomName() + "\" 群聊。";
        Date date = new Date();
        String imUserId = imUser.getId();
        List<String> arrayListUserId = Arrays.asList(userIds);
        List<String> listUserId = new ArrayList<>();
        listUserId.addAll(arrayListUserId);
        String[] receiveUserIds = userIds;
        if (isCreate) {
            if (!listUserId.contains(imUserId)) {
                listUserId.add(imUserId);
            }
        } else {
            if (listUserId.contains(imUserId)) {
                listUserId.remove(imUserId);
            }
            //群聊内添加人员后  需要推送消息给群内已有人员 还有刚刚添加的人员
            Set<String> setIds = imRoomUserService.getRoomUserIdsByRoomId(roomId);
            receiveUserIds= setIds.toArray(new String[]{});
            int strRLength = receiveUserIds.length;
            int strUlength = userIds.length;
            receiveUserIds = Arrays.copyOf(receiveUserIds, strRLength+strUlength);//数组扩容
            System.arraycopy(userIds, 0, receiveUserIds, strRLength, strUlength);
        }
        List<ImSystemMessage> messageList = new ArrayList<>();
        List<ImRoomUser> allRoomUser = new ArrayList<>();
        //入群聊成员表
        for (String userId : listUserId) {
            ImRoomUser imRoomUser = new ImRoomUser();
            imRoomUser.setId(UUIDUtils.getUUIDFor32());
            imRoomUser.setJoinBy(imUser.getId());
            imRoomUser.setJoinTime(date);
            imRoomUser.setUserId(userId);
            imRoomUser.setRoomId(roomId);
            allRoomUser.add(imRoomUser);
            if (!userId.equals(imUserId)) {
                messageList.add(new ImSystemMessage(UUIDUtils.getUUIDFor32(), "", userId, content, ""));
            }
        }
        count = dao.addList(allRoomUser);
        if (!messageList.isEmpty()) {
            imSystemMessageService.addList(messageList);
        }
        if(addUserNames.length>0){
            String userNames = StringUtils.join(addUserNames,"，");
            imRoom.setAddUserContent("\""+imUser.getUsername()+"\"邀请\""+userNames+"\"加入此群聊");
        }
        imConnertorImpl.pushSystemMessage(JSONObject.toJSONString(imRoom), Constants.SystemMsgType.ADD_ROOM_USER, receiveUserIds);
        return count;
    }

    /**
     * 群聊里面删除人员
     *
     * @param roomId  群ID
     * @param userIds 删除人员数组
     * @return 删除条数
     */
    @Transactional(rollbackFor = Exception.class)
    public int delRoomUsers(String roomId, String[] userIds, String roomName,boolean isSignOut) {
        int num = dao.delRoomUsers(roomId, userIds);
        if(!isSignOut){
            List<ImSystemMessage> list = new ArrayList<>();
            String content = "你已被移出 \"" + roomName + "\" 群聊。";
            for (String userId : userIds) {
                list.add(new ImSystemMessage(UUIDUtils.getUUIDFor32(), "", userId, content, ""));
            }
            if (list.size() > 0) {
                imSystemMessageService.addList(list);
                imConnertorImpl.pushSystemMessage(roomId, Constants.SystemMsgType.DEL_ROOM_USER, userIds);
            }
        }
        return num;
    }

    /**
     * 某个群聊里面删除所有人员
     *
     * @param roomId 群ID
     * @return 删除条数
     */
    @Transactional(rollbackFor = Exception.class)
    public int delByRoomId(String roomId) {
        return dao.delByRoomId(roomId);
    }

    /**
     * 查询当前用户是否在某个群聊内
     *
     * @param roomId 群ID
     * @return boolean
     */
    public boolean qryCurrentUserExistOneRoom(String roomId) {
        String currentUserId = ContextUtil.getCurrentUserId();
        ImUser imUser = imUserService.getByUserId(currentUserId);
        int num = dao.selectCountByRoomIdAndUserId(roomId, imUser.getId());
        return num > 0 ? true : false;
    }

    /**
     * 查询某个用户是否在某个群聊内
     *
     * @param userId 某个用户ID
     * @param roomId 群ID
     * @return boolean
     */
    public boolean qryUserExistOneRoom(String userId, String roomId) {
        int num = dao.selectCountByRoomIdAndUserId(roomId, userId);
        return num > 0 ? true : false;
    }


}
